package com.kpmg.datalake.autopackage.service.impl;

import com.kpmg.datalake.autopackage.service.ExcelTemplateService;
import com.kpmg.datalake.autopackage.service.PkgAutoService;
import com.kpmg.datalake.autopackage.vo.ExcelTemplate;
import com.kpmg.datalake.autopackage.vo.PackageParamVO;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.exception.BusinessException;
import com.kpmg.datalake.common.service.CommonExecuteService;
import com.kpmg.datalake.common.utils.AssertUtil;
import com.kpmg.datalake.common.utils.ExceptionUtil;
import com.kpmg.datalake.common.utils.ResponseUtils;
import com.kpmg.datalake.common.vo.ServerResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author changpengye
 * @author alex
 */
@Service
public class PkgAutoServiceImpl implements PkgAutoService {

    private static final Logger logger = LoggerFactory.getLogger(PkgAutoServiceImpl.class);

    @Resource
    private CommonExecuteService executeService;
    @Resource
    private ExcelTemplateService excelTemplateService;

    /**
     * <p>Title:       queryData</p>
     * <p>Description: 按SQL查询数据</p>
     *
     * @param packageParamVO packageParamVO
     * @return ServerResponse
     */
    @Override
    public ServerResponse<ArrayList<Map<String, Object>>> queryData(PackageParamVO packageParamVO) {
        ServerResponse<ArrayList<Map<String, Object>>> result;
        try {
            AssertUtil.assertNotEmpty(packageParamVO.getProjectId(), "projectId不能为空");
            AssertUtil.assertNotEmpty(packageParamVO.getQuerySql(), "querySQL不能为空");
            logger.info("SQL:{}", packageParamVO.getQuerySql());
            List<Map<String, Object>> data = executeService.queryListByString(packageParamVO.getProjectId(), packageParamVO.getQuerySql());
            result = ServerResponse.createBySuccess(new ArrayList<>(data));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ExceptionUtil.getExceptionMsg(e);
        }
        return result;
    }

    /**
     * <p>Title:       upRemark</p>
     * <p>Description: 按SQL更新备注</p>
     *
     * @param packageParamVO packageParamVO
     * @return ServerResponse
     */
    @Override
    public ServerResponse<String> upRemark(PackageParamVO packageParamVO) {

        ServerResponse<String> result;
        try {
            AssertUtil.assertNotEmpty(packageParamVO.getProjectId(), "projectId不能为空");
            AssertUtil.assertNotEmpty(packageParamVO.getQuerySql(), "querySQL不能为空");
            logger.info("SQL:{}", packageParamVO.getQuerySql());
            Integer row = executeService.updateByString(packageParamVO.getProjectId(), packageParamVO.getQuerySql());
            if (row == null || row <= 0) {
                throw new BusinessException(ResultCodeEnum.CODE4014, "按照sql跟新备注失败");
            }
            result = ServerResponse.createBySuccess();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ExceptionUtil.getExceptionMsg(e);
        }
        return result;
    }

    @Override
    public void pkgDownload(String id, HttpServletRequest request, HttpServletResponse response) {
        ExcelTemplate model = excelTemplateService.selectByPrimaryKey(id);
        if (model == null) {
            String error = "message:模板不存在";
            logger.error(error);
            return;
        }
        String filePath = model.getFileUrl();
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        ResponseUtils.setZipDownloadResponseHeader(fileName, request, response);

        try (FileInputStream inputStream = new FileInputStream(filePath);) {
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("下载查询请求结果文件异常:{}", e.getMessage());

        }
    }


}
